package com.guchenbo.example.socket.nio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author guchenbo
 * @Date 2018/10/26.
 */
public class EchoServer {
    protected static final Logger log = LoggerFactory.getLogger(EchoServer.class);

    public static void main(String[] args) {
        EchoServer server = new EchoServer();
        server.start();
    }

    private void start() {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(9999));
            serverSocketChannel.configureBlocking(false);

            Selector selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {
                int i = selector.select();
                if (i > 0) {
                    Set<SelectionKey> keySet = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = keySet.iterator();

                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        NioUtils.log(key);



                        if (key.isAcceptable()) {
                            log.info("accept");
                            ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                            SocketChannel client = channel.accept();
//                            client.configureBlocking(false);
//                            client.register(selector, SelectionKey.OP_CONNECT);

                            ByteBuffer buffer = ByteBuffer.allocate(32);
                            buffer.put((byte) 0);
                            buffer.flip();
                            client.write(buffer);
                        } else if (key.isReadable()) {

                        }

                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
